package com.central.apps.handler.project;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处理项目启动业务逻辑
 *
 * @author lidachao
 * @date 2023/3/4
 */
@Component
@Slf4j
public class ProjectStartHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if(flowNode.getId().equals("complete") && op.isFlag()) {
            // 查询项目信息
            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_proaccount where id = " + id);
            String scheduleStatus = MapUtils.getString(list.get(0), "proschedulestatus");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = dateFormat.parse(MapUtils.getString(list.get(0), "startdate"));
            Date date = new Date();

            StringBuilder sql = new StringBuilder();
            sql.append("update gq_proaccount set prostatus = '进行中'");

            // 判断是否提前完工
            if (date.before(startDate)) {
                sql.append(", proschedulestatus = '提前开工'");
            } else {
                if (StringUtils.isEmpty(scheduleStatus)) {
                    sql.append(", proschedulestatus = '按期进行'");
                }
            }

            sql.append(" where id = ").append(id);

            // 更新项目状态
            handlerService.updateBySql(sql.toString());

            // 任务下发
            handlerService.updateBySql("update gq_scheduleplantask set isissued = 1 where proid = " + id);
            // 任务根节点启动
            handlerService.updateBySql("update gq_scheduleplantask set status = '进行中' where parentId = 0 and proid = " + id);
        }

        return null;
    }
}
